package apis

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"strconv"
	"strings"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	dto2 "tuowei.com/common/dto"
	Beans "tuowei.com/pkg/sing/beans"
	HttpHelper "tuowei.com/pkg/sing/http_utils"
	"tuowei.com/pkg/sing/sign_service"
)

type SysOfflineCourse struct {
	api.Api
}

// GetPage
// @Summary 列表课程信息数据
// @Description 获取JSON
// @Tags 课程
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user [get]
// @Security Bearer
func (e SysOfflineCourse) GetPages(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysOfflineCourseList, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	listresp := make([]models.SysOfflineCourseList, 0)
	for i, _ := range list {
		list[i].CourseType = "offline"
		listresp = append(listresp, list[i])
	}

	e.PageOK(listresp, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e SysOfflineCourse) GetPagesApp(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.Default(c.Request.Method, c.ContentType())).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.Status = 1
	//规避直辖市
	req.Province = strings.Replace(req.Province, "市", "", -1)
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysOfflineCourseList, 0)
	var count int64

	err = s.GetAppPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	listresp := make([]models.SysOfflineCourseList, 0)
	for i, _ := range list {
		list[i].CourseType = "offline"
		listresp = append(listresp, list[i])
	}

	e.PageOK(listresp, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 创建课程
// @Description 获取JSON
// @Tags 课程
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysOfflineCourseInsertReq true "课程数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-course [post]
// @Security Bearer
func (e SysOfflineCourse) Insert(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.GetId(), "创建成功")
}

func (e SysOfflineCourse) ChangeStatus(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseUpdateStatusReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.UpdateStatus(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

func (e SysOfflineCourse) Update(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除班级数据
// @Description 删除数据
// @Tags 班级
// @Param userId path int true "classId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{classId} [delete]
// @Security Bearer
func (e SysOfflineCourse) Delete(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 设置删除人
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// Get
// @Summary 获取用户
// @Description 获取JSON
// @Tags 用户
// @Param userId path int true "用户编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-user/{userId} [get]
// @Security Bearer
func (e SysOfflineCourse) Get(c *gin.Context) {
	s := service.SysOfflineCourse{}
	req := dto.SysOfflineCourseById{}
	s1 := service.SysCourseGift{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		MakeService(&s1.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var data models.SysOfflineCourse
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &data)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	arr := make([]int, 0)
	if data.BindingOnlineId != "" {
		bindingOnlineIds := strings.Split(data.BindingOnlineId, ",")
		for _, v := range bindingOnlineIds {
			vv, err := strconv.Atoi(v)
			if err == nil {
				arr = append(arr, vv)
			}
		}
	}
	list, err := s1.Get(data.CourseId, "offline")
	result := models.SysOfflineCourseGetDetail{
		CourseId:   data.CourseId,
		CourseType: "offline",
		OfflineStep1: models.OfflineStep1{
			SerialNum:      data.SerialNum,
			Subject:        data.Subject,
			Name:           data.Name,
			Cover:          data.Cover,
			Outline:        data.Outline,
			Price:          data.Price,
			Introduction:   data.Introduction,
			CourseDuration: data.CourseDuration,
			Status:         data.Status,
			PublicRange:    data.PublicRange,
			Province:       data.Province,
			LBTUrl:         data.LBTUrl,
		},
		OfflineStep2: models.OfflineStep2{
			LecturerId:        data.LecturerId,
			BelongingProvince: data.BelongingProvince,
			ClassType:         data.ClassType,
			City:              data.City,
			Area:              data.Area,
			DeptId:            data.DeptId,
			Explain:           data.Explain,
			CourseDesExplain:  data.CourseDesExplain,
			TrainingDays:      data.TrainingDays,
			BindingOnlineId:   arr,
			Telephone:         data.Telephone,
			CourseGift:        list,
			ContactUrl:        data.ContactUrl,
			FileId:            data.FileId,
			Qq:                data.Qq,
		},
		ControlBy: data.ControlBy,
		ModelTime: data.ModelTime,
		Lecture:   data.Lecture,
	}

	e.OK(result, "查询成功")
}

func (e SysOfflineCourse) DeleteESign(ctx *gin.Context) {
	e.MakeContext(ctx).MakeOrm()
	id, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	err = e.Orm.Delete(&models.ESignContract{}, id).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	e.OK(nil, "删除成功")
}

func (e SysOfflineCourse) GetESignList(ctx *gin.Context) {
	req := dto2.Pagination{}
	err := e.MakeContext(ctx).Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).MakeOrm().Errors
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	lists := make([]models.ESignContract, 0)
	var count int64
	err = e.Orm.Scopes(
		dto2.Paginate(req.GetPageSize(), req.GetPageIndex()),
	).Find(&lists).Limit(-1).Offset(-1).Count(&count).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	e.PageOK(lists, int(count), req.GetPageIndex(), req.GetPageSize(), "success")
}

func (e SysOfflineCourse) BindESignTemplate(ctx *gin.Context) {
	req := dto.BindESignTemplate{}
	s := service.SysOfflineCourse{}
	err := e.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	err = s.BindESignTemplate(req)
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	e.OK(nil, "success")
}

func (e SysOfflineCourse) GetCreateTemplateUrl(ctx *gin.Context) {
	req := dto.GetCreateTemplateUrl{}
	err := e.MakeContext(ctx).Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	var jsonStr string
	if data, err := json.Marshal(req); err == nil {
		jsonStr = string(data)
	}
	sign_service.EsignInitService()
	r, status := HttpHelper.SendCommHttp("/v3/doc-templates/doc-template-create-url", jsonStr, http.MethodPost)
	if status != 200 {
		e.Error(http.StatusInternalServerError, nil, "请求e电签接口错误")
		return
	}
	rsp := Beans.GetCreateTemplateUrlRsp{}
	json.Unmarshal(r, &rsp)
	if rsp.Code != 0 {
		e.Error(http.StatusInternalServerError, nil, rsp.Message)
		return
	}
	e.OK(rsp.Data, rsp.Message)

}

func (e SysOfflineCourse) GetTemplateDetail(ctx *gin.Context) {
	req := dto.GetTemplateDetail{}
	err := e.MakeContext(ctx).MakeOrm().Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		e.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	rsp, err := HttpHelper.GetTemplateDetail(req.DocTemplateId)
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	if rsp.Code != 0 {
		e.Error(http.StatusInternalServerError, err, rsp.Message)
		return
	}
	e.OK(rsp.Data, rsp.Message)
}
